package com.yuxl.admin.common.socket.handler;

import com.yuxl.admin.common.socket.annotation.SocketHandle;
import com.yuxl.admin.common.socket.domain.SocketInMessage;
import com.yuxl.admin.common.socket.utils.SocketMessageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;


@Slf4j
@Component
@RequiredArgsConstructor
public class ChatSocketHandler {

    private final SocketMessageUtil socketMessageUtil;

    @SocketHandle(path = "/chat")
    public Mono<Void> handleChatMessage(SocketInMessage message, WebSocketSession session) {
        log.debug("收到来自用户 {} 的聊天消息: {}", message.getUsername(), message.getPath());
        String response = String.format("用户 %s 说: %s", message.getUsername(), message.getPath());
        
        return socketMessageUtil.sendMessageToAllUsers(message);
    }

    @SocketHandle(path = "/private")
    public Mono<Void> handlePrivateMessage(SocketInMessage message, WebSocketSession session) {
        String to = message.getTo();
        return socketMessageUtil.sendMessageToUser(message)
                .flatMap(sent -> {
                    if (sent) {
                        return socketMessageUtil.sendMessageToSession(session, "私人消息已发送给 " + to);
                    } else {
                        return socketMessageUtil.sendMessageToSession(session, "用户 " +to + " 不可用");
                    }
                });
    }
}
